<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="fba">
              <!-- <a-input v-model:value.trim="oceanBulkCargoAddressWhere.name" placeholder="请输入" @keyup.enter="oceanBulkCargoAddressReload" @change="oceanBulkCargoAddressReload" allow-clear />-->
              <a-input v-model:value.trim="oceanBulkCargoAddressWhere.fba" placeholder="请输入名称fba" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="oceanBulkCargoAddressReload">查询</a-button>
                <a-button @click="oceanBulkCargoAddressReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="oceanBulkCargoAddressTableRef" row-key="id" :columns="columns" :datasource="datasource"
        :scroll="{ x: 1000 }">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="oceanBulkCargoAddressOpenEdit()"
              v-any-permission="['ocean:oceanBulkCargoAddress:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>新建</span>
            </a-button>
            <a-upload :before-upload="importFile" :show-upload-list="false" accept=".xls,.xlsx">
              <a-button type="primary" class="ele-btn-icon">导入</a-button>
            </a-upload>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="oceanBulkCargoAddressOpenEdit(record)"
                v-any-permission="['ocean:oceanBulkCargoAddress:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="oceanBulkCargoAddressRemove(record)">
                <a class="ele-text-danger" v-any-permission="['ocean:oceanBulkCargoAddress:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 海运散货地址库添加、修改弹窗 -->
    <ele-modal :width="460" v-model:visible="oceanBulkCargoAddressVisible_modal" :confirm-loading="loading"
      :title="oceanBulkCargoAddressIsUpdate ? '修改海运散货地址库' : '新建海运散货地址库'" position="center"
      :body-style="{ paddingBottom: '8px' }" @ok="oceanBulkCargoAddressSave" :maskClosable="false">
      <a-form ref="oceanBulkCargoAddressFormRef" :model="oceanBulkCargoAddressForm" :rules="oceanBulkCargoAddressRules"
        :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="FBA仓库代码" name="fba">
          <a-input allow-clear :maxlength="200" placeholder="请输入FBA仓库代码" v-model:value="oceanBulkCargoAddressForm.fba"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="联系人" name="contacts">
          <a-input allow-clear :maxlength="200" placeholder="请输入联系人" v-model:value="oceanBulkCargoAddressForm.contacts"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="公司名" name="company">
          <a-input allow-clear :maxlength="200" placeholder="请输入公司名" v-model:value="oceanBulkCargoAddressForm.company"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="联系电话" name="phone">
          <a-input allow-clear :maxlength="200" placeholder="请输入联系电话" v-model:value="oceanBulkCargoAddressForm.phone"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="地址1" name="addr1">
          <a-input allow-clear :maxlength="200" placeholder="请输入地址1" v-model:value="oceanBulkCargoAddressForm.addr1"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="城市" name="city">
          <a-input allow-clear :maxlength="200" placeholder="请输入城市" v-model:value="oceanBulkCargoAddressForm.city"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="省份" name="province">
          <a-input allow-clear :maxlength="200" placeholder="请输入省份" v-model:value="oceanBulkCargoAddressForm.province"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="国家" name="country">
          <a-input allow-clear :maxlength="200" placeholder="请输入国家" v-model:value="oceanBulkCargoAddressForm.country"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="邮编" name="postal">
          <a-input allow-clear :maxlength="200" placeholder="请输入邮编" v-model:value="oceanBulkCargoAddressForm.postal"
            autocomplete="off" />
        </a-form-item>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { utils, read } from 'xlsx';
import { TIME_OUT } from '@/config/damon';

import { pageOceanBulkCargoAddress, removeOceanBulkCargoAddress, addOceanBulkCargoAddress, updateOceanBulkCargoAddress } from '@/api/ocean/oceanBulkCargoAddress';

// 导入数据的列
const importTitle = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G']);

// 导入的数据
const importData = ref([]);

// 导入数据二维数组形式
const importDataAoa = ref([]);

/* 导入本地 excel 文件 */
const importFile = (file) => {
  if (
    ![
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ].includes(file.type)
  ) {
    message.error('只能选择 excel 文件');
    return false;
  }
  if (file.size / 1024 / 1024 > 20) {
    message.error('大小不能超过 20MB');
    return false;
  }
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target?.result);
    const workbook = read(data, { type: 'array' });
    const sheetNames = workbook.SheetNames;
    const worksheet = workbook.Sheets[sheetNames[0]];
    // 解析成二维数组
    const aoa = utils.sheet_to_json(worksheet, { header: 1 });
    // 生成表格需要的数据
    let list = [];
    let maxCols = 0;
    let title = [];
    aoa.forEach((d) => {
      if (d.length > maxCols) {
        maxCols = d.length;
      }
      const row = {};
      for (let i = 0; i < d.length; i++) {
        const key = getCharByIndex(i);
        row[key] = d[i];
        row['__colspan__' + key] = 1;
        row['__rowspan__' + key] = 1;
      }
      list.push(row);
    });
    for (let i = 0; i < maxCols; i++) {
      title.push(getCharByIndex(i));
    }
    importTitle.value = title;
    importData.value = list;
    importDataAoa.value = aoa;
    importData.value.forEach((ele) => {
      let aa = {}
      aa.fba = ele.C
      aa.contacts = ele.D
      aa.company = ele.E
      aa.phone = ele.F
      aa.addr1 = ele.H
      aa.city = ele.K
      aa.province = ele.L
      aa.country = ele.M
      aa.postal = ele.N
      addOceanBulkCargoAddress(aa).then((msg) => {
        message.success(msg);
      }).catch((e) => {
        message.error(e.message);
      });
    })
  };
  reader.readAsArrayBuffer(file);
  return false;
};
/* 生成Excel列字母序号 */
const getCharByIndex = (index) => {
  const chars = [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ];
  if (index < chars.length) {
    return chars[index];
  }
  const n = parseInt(String(index / chars.length));
  const m = index % chars.length;
  return chars[n] + chars[m];
};
// 表格实例
const oceanBulkCargoAddressTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (oceanBulkCargoAddressTableRef.value?.tableIndex ?? 0)
  },
  {
    title: 'FBA仓库代码',
    dataIndex: 'fba',
    key: 'fba',
    // sorter: true
  },
  {
    title: '联系人',
    dataIndex: 'contacts',
    key: 'contacts',
    // sorter: true
  },
  {
    title: '公司名',
    dataIndex: 'company',
    key: 'company',
    // sorter: true
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    // sorter: true
  },
  {
    title: '地址1',
    dataIndex: 'addr1',
    key: 'addr1',
    // sorter: true
  },
  {
    title: '城市',
    dataIndex: 'city',
    key: 'city',
    // sorter: true
  },
  {
    title: '省份',
    dataIndex: 'province',
    key: 'province',
    // sorter: true
  },
  {
    title: '国家',
    dataIndex: 'country',
    key: 'country',
    // sorter: true
  },
  {
    title: '邮编',
    dataIndex: 'postal',
    key: 'postal',
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: oceanBulkCargoAddressWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  return pageOceanBulkCargoAddress({ ...where, ...orders, page, limit });
};

/* 搜索 */
const oceanBulkCargoAddressReload = () => {
  oceanBulkCargoAddressTableRef?.value?.reload({ page: 1, where: oceanBulkCargoAddressWhere });
};
const oceanBulkCargoAddressReload2 = () => {
  oceanBulkCargoAddressTableRef?.value?.reload();
};

let oceanBulkCargoAddressWhere_timeout = 0
watch(() => oceanBulkCargoAddressWhere, (val) => {
  clearTimeout(oceanBulkCargoAddressWhere_timeout)
  oceanBulkCargoAddressWhere_timeout = setTimeout(() => {
    oceanBulkCargoAddressReload();
  }, TIME_OUT);
},
  { deep: true }
)

/*  重置 */
const oceanBulkCargoAddressReset = () => {
  resetFields();
  oceanBulkCargoAddressReload();
};

/* 删除单个 */
const oceanBulkCargoAddressRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeOceanBulkCargoAddress(record.id).then((msg) => {
    hide();
    message.success(msg);
    oceanBulkCargoAddressReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const oceanBulkCargoAddressCurrent = ref(null);

// 弹窗是否打开
const oceanBulkCargoAddressVisible_modal = ref(false);

// 是否是修改
const oceanBulkCargoAddressIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const oceanBulkCargoAddressFormRef = ref(null);

// 表单数据
const { form: oceanBulkCargoAddressForm, resetFields: oceanBulkCargoAddressResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});

// 表单验证规则
const oceanBulkCargoAddressRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});

/* 打开编辑弹窗 */
const oceanBulkCargoAddressOpenEdit = (record) => {
  oceanBulkCargoAddressResetFormFields();
  oceanBulkCargoAddressFormRef.value?.clearValidate();
  oceanBulkCargoAddressCurrent.value = record ?? {};
  oceanBulkCargoAddressVisible_modal.value = true;
  Object.assign(oceanBulkCargoAddressForm, record ?? {});
  oceanBulkCargoAddressIsUpdate.value = !!record;
};

/* 保存编辑 */
const oceanBulkCargoAddressSave = () => {
  if (!oceanBulkCargoAddressFormRef.value) {
    return;
  }
  oceanBulkCargoAddressFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = oceanBulkCargoAddressIsUpdate.value ? updateOceanBulkCargoAddress : addOceanBulkCargoAddress;
    saveOrUpdate(oceanBulkCargoAddressForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      oceanBulkCargoAddressVisible_modal.value = false;
      oceanBulkCargoAddressReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<script>
export default {
  name: 'DemoTest'
};
</script>

